require "lib/wave"

module MediaTools
  
  class PcmWavExtractor
    include MicrosoftWavPcmReader
    
    def extract src_io, out_io, samples_range
      @samples_range = samples_range
      @writer = MicrosoftWavPcmWriter.new(out_io)
      read_all src_io
    end
    
    def on_format(format)
      @format = format
      @writer.write_headers_begin format
    end
    private :on_format
    
    def on_data(length, io)
      start_pos = io.pos
      end_pos = io.pos + length

      writer_start_pos = start_pos + @samples_range.begin * @format.block_align
      writer_end_pos = start_pos + (@samples_range.exclude_end? ? @samples_range.end : @samples_range.end + 1) * @format.block_align

      writer_start_pos = start_pos if start_pos > writer_start_pos
      writer_end_pos = end_pos if end_pos < writer_end_pos

      io.pos = writer_start_pos
      buffer = io.read(writer_end_pos - writer_start_pos)
      @writer.io.write(buffer)
    end
    private :on_data
    
    def on_eof
      @writer.write_headers_end
    end
    private :on_eof
  end
  
end